<template>
    <div class="content_container">
        <div class="left_container management">
            <div class="title_management">
                <h2>用户管理</h2>
            </div>
            <div class="content_management">

                <div class="select_management">
                    <div class="title">用户类型：</div>
                    <div class="content">
                        <el-select v-model="queryParams.roleId" placeholder="请选择用户类型" clearable @change="changeType">
                            <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="title">注册日期：</div>
                    <div class="content">
                        <el-date-picker v-model="queryParams.searchTimes" type="monthrange" align="right" unlink-panels
                            range-separator="至" value-format="yyyy-MM" start-placeholder="开始月份" end-placeholder="结束月份"
                            :picker-options="pickerOptions" clearable @change="changeDate">
                        </el-date-picker>
                    </div>
                    <div class="title">关键字：</div>
                    <div class="content">
                        <el-input v-model="queryParams.searchKeyword" @input="queryRolesList" placeholder="手机号/用户名"
                            clearable></el-input>
                    </div>
                    <el-button type="success" size="small" icon="el-icon-plus" style="margin-left: 10px;"
                        @click="addOrEditUser(null)" v-if="btnList.includes('addUser')">新增用户</el-button>
                    <!-- <el-button size="small" icon="el-icon-user" style="margin-left: 10px;"
                        @click="handleEdit($event, null, '分配角色')" :disabled="Boolean(!selectList.length)"
                        v-if="btnList.includes('assginRole')">分配角色</el-button> -->
                    <el-button size="small" icon="el-icon-s-operation" style="margin-left: 10px;" type="primary" plain
                        @click="handleEdit($event, null, '分配内存')" :disabled="Boolean(!selectList.length)"
                        v-if="btnList.includes('space')">配置</el-button>
                    <el-button size="small" icon="el-icon-warning-outline" style="margin-left: 10px;" type="info"
                        :disabled="whetherShow('free')" @click="freezeOrThawUser($event, null, 'free')"
                        v-if="btnList.includes('freeze')">批量冻结</el-button>
                    <el-button size="small" icon="el-icon-warning-outline" style="margin-left: 10px;" type="primary"
                        :disabled="whetherShow('thaw')" @click="freezeOrThawUser($event, null, 'thaw')"
                        v-if="btnList.includes('thaw')">批量解冻</el-button>
                    <el-button type="warning" size="small" icon="el-icon-brush" plain
                        :disabled="Boolean(!selectList.length)" @click="clearUserSpace($event, null)"
                        v-if="btnList.includes('removeMemory')">批量清空</el-button>
                    <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteUser"
                        :disabled="Boolean(!selectList.length)" v-if="btnList.includes('delete')">批量删除</el-button>
                    <el-button type="danger" size="small" icon="el-icon-circle-close" @click="clearUser"
                        v-if="btnList.includes('clear')">一键清理</el-button>
                </div>
                <!-- table -->
                <div class="table_management">
                    <el-table :data="tableData" style="width: 100%" border stripe :header-cell-style="getRowClass"
                        @selection-change="handleSelectionChange" :max-height="maxHeight" v-loading="loading">
                        <el-table-column type="selection" width="55" align="center" :selectable="selectable">
                        </el-table-column>
                        <el-table-column label="注册日期" prop="createDate" align="center">
                            <!-- <template slot-scope="scope">
                                <i class="el-icon-time"></i>
                                <span style="margin-left: 10px">{{ scope.row.createDate }}</span>
                            </template> -->
                        </el-table-column>
                        <el-table-column label="用户名" prop="userName" align="center">
                        </el-table-column>
                        <el-table-column label="用户类型" prop="userType" align="center">
                        </el-table-column>
                        <el-table-column label="最大运行数量" prop="runLimitCount" align="center">
                        </el-table-column>
                        <el-table-column label="最大队列数量" prop="waitLimitCount" align="center">
                        </el-table-column>
                        <el-table-column label="已用内存" align="center">
                            <template slot-scope="scope">
                                <span>{{ $size2Str(scope.row.hasUsedSize) }}/{{ $size2Str(scope.row.maxSpace) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" min-width="200px">
                            <template slot-scope="scope">
                                <el-tooltip class="item" effect="dark" content="编辑用户" placement="top"
                                    v-if="btnList.includes('editUser')">
                                    <el-button size="small" icon="el-icon-edit" @click="addOrEditUser(scope.row)"
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>

                                <!-- <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                                    <el-button size="mini" @click="handleEdit($event, scope.row, '分配角色')"
                                        icon="el-icon-user" :disabled="scope.row.initUser"></el-button>
                                </el-tooltip> -->

                                <el-tooltip class="item" effect="dark" content="配置" placement="top"
                                    v-if="btnList.includes('space')">
                                    <el-button size="mini" type="primary" @click="handleEdit($event, scope.row, '配置')"
                                        icon="el-icon-s-operation" plain
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>

                                <el-tooltip class="item" effect="dark" content="冻结用户" placement="top"
                                    v-if="scope.row.enable && btnList.includes('freeze') && scope.row.userType !== '超级管理员'">
                                    <el-button size="mini" type="info"
                                        @click="freezeOrThawUser($event, scope.row.id, 'free')"
                                        icon="el-icon-warning-outline"
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>

                                <el-tooltip class="item" effect="dark" content="解冻用户" placement="top"
                                    v-if="!scope.row.enable && btnList.includes('freeze') && scope.row.userType !== '超级管理员'">
                                    <el-button size="mini" type="primary"
                                        @click="freezeOrThawUser($event, scope.row.id, 'thaw')"
                                        icon="el-icon-warning-outline"
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>

                                <el-tooltip class="item" effect="dark" content="清空内存" placement="top"
                                    v-if="btnList.includes('removeMemory') && scope.row.userType !== '超级管理员'">
                                    <el-button size="mini" type="warning" @click="clearUserSpace($event, scope.row.id)"
                                        icon="el-icon-brush" plain
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>

                                <el-tooltip class="item" effect="dark" content="删除" placement="top"
                                    v-if="btnList.includes('delete') && scope.row.userType !== '超级管理员'">
                                    <el-button size="mini" type="danger" @click="deleteUser($event, scope.row.id)"
                                        icon="el-icon-delete"
                                        :disabled="manageControl(scope.row.userType, scope.row.id)"></el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="createDate">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="pageNo" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                            layout="->,total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <!-- dialog -->
        <el-dialog title="配置用户" :visible.sync="dialogVisible" :width="pointsWidth" :close-on-click-modal="false"
            :close-on-press-escape="false" v-dialogDrag>
            <el-form ref="form" :model="userConfig" label-width="120px" label-position="left">
                <el-form-item label="内存(G):">
                    <el-slider v-model="userConfig.memoryValue" :max="100" :min="0.5" :step="0.5">
                    </el-slider>
                </el-form-item>

                <el-form-item label="运行数量:">
                    <el-slider v-model="userConfig.runLimitCount" :max="50" :min="1" :step="1">
                    </el-slider>
                </el-form-item>

                <el-form-item label="队列数量:">
                    <el-slider v-model="userConfig.waitLimitCount" :max="100" :min="1" :step="1">
                    </el-slider>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="determine">确 定</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>

        <!-- 新增编辑用户 -->
        <el-dialog :title="userTitle" :visible.sync="userDialogVisible" :width="userWidth" v-dialogDrag>
            <div class="user_details">
                <el-form ref="form" :model="userForm" label-width="80px" label-position="left">
                    <el-form-item label="手机号">
                        <el-input v-model.trim="userForm.mobilePhone" placeholder="请输入用户手机号" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="用户名">
                        <el-input v-model.trim="userForm.userName" placeholder="请输入用户名" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="角色" v-if="userForm.userName !== 'superadmin'">
                        <el-select v-model="userForm.roleId" placeholder="请选择用户类型" clearable>
                            <el-option v-for="item in options" :key="item.value" :value="item.value" :label="item.label">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="密码">
                        <el-input v-model.trim="userForm.password" placeholder="请输入用户密码" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱">
                        <el-input v-model.trim="userForm.email" placeholder="请输入用户邮箱" clearable></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="userDetermine">确 定</el-button>
                <el-button @click="userDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
        <!-- 清理 -->
        <el-dialog title="一键清理" :visible.sync="clearVisible" width="500px" :close-on-click-modal="false"
            :close-on-press-escape="false" v-dialogDrag>
            <div class="clear_dom">
                <el-input-number v-model="params.num" :min="1" style="width:150px;margin-right:20px;"></el-input-number>
                <el-radio-group v-model="params.unit">
                    <el-radio label="日">日</el-radio>
                    <el-radio label="月">月</el-radio>
                    <el-radio label="年">年</el-radio>
                </el-radio-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="clear">确 定</el-button>
                <el-button @click="clearVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import mixins from './mixins';
import { deepClone, throttle } from '@/utils';
import {
    getUserListRequest,
    getRoleSelectListRequest,
    deleteUserRequest,
    freezeOrThawUserRequest,
    clearUserSpaceRequest,
    adjustUserRoleRequest,
    adjustUserSpaceRequest,
    saveUserRequest,
    cleanInactiveUserSpaceRequest
} from '@/api/management'
export default {
    name: 'GenecloudUiIndex',
    mixins: [mixins],
    data() {
        return {
            id: JSON.parse(localStorage.getItem('userInfo')).id,
            role: JSON.parse(localStorage.getItem('userInfo')).role,
            params: {
                num: 1,
                unit: '日',
            },
            clearVisible: false,
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                roleId: "",
                searchKeyword: '',
                searchTimes: []
            },
            btnList: this.$store.state.login.buttonPermissionList,
            //用户列表
            tableData: [],
            //用户类型
            options: [],
            value: '',
            input: '',
            pickerOptions: {
                shortcuts: [{
                    text: '本月',
                    onClick(picker) {
                        picker.$emit('pick', [new Date(), new Date()]);
                    }
                }, {
                    text: '今年至今',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date(new Date().getFullYear(), 0);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近六个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setMonth(start.getMonth() - 6);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            //分页器
            total: 10,
            pageSize: 10,
            pageNo: 1,
            //分配
            selectList: [],
            dialogVisible: false,
            title: '',
            chaneRole: null,
            pointsWidth: '460px',
            marks: {
                0.5: '0.5G',
                20: '20G'
            },
            rowList: null,
            //新增删除用户
            userTitle: null,
            userDialogVisible: false,
            userWidth: '500px',
            userForm: {
                id: '',
                mobilePhone: '',
                userName: '',
                password: '',
                email: '',
                roleId: ''
            },
            userConfig: {
                chaneRole: null,
                memoryValue: null,
                runLimitCount: null,
                waitLimitCount: null,
            }
        };
    },
    created() {
        this.getList(this.queryParams)
        this.getRoleSelect()
    },
    mounted() {

    },

    methods: {
        async getRoleSelect() {
            const res = await getRoleSelectListRequest()
            if (res.code !== 200) return this.$message.error(res.message)
            this.options = res.data.reduce((pre, item) => {
                pre.push({
                    label: item.roleName,
                    value: item.id
                })
                return pre
            }, [])
        },
        async getList(queryParams) {
            const res = await getUserListRequest(queryParams)
            if (res.code !== 200) return this.$message.error(res.code)
            this.tableData = res.data.list || []
            this.loading = false
            this.total = res.data.total
        },
        handleEdit(event, row, title) {
            // this.title = title
            this.dialogVisible = true
            if (row) {
                this.rowList = deepClone(row)
                this.userConfig = deepClone(row)
                let num = this.$size2Str(row.maxSpace)
                this.userConfig.memoryValue = Number(num.substring(0, num.length - 1)) == 512 ? 0.5 : Number(num.substring(0, num.length - 1))
            } else {
                this.userConfig.memoryValue = 0
                this.userConfig.runLimitCount = 0
                this.userConfig.waitLimitCount = 0
            }

        },
        handleSelectionChange(val) {
            this.selectList = val;
        },
        handleSizeChange(val) {
            this.pageSize = val
            this.queryParams.pageSize = val
            this.getList(this.queryParams)
        },
        handleCurrentChange(val) {
            this.pageNo = val
            this.queryParams.pageNo = val
            this.getList(this.queryParams)
        },
        //用户类型筛选
        changeType(type) {
            this.getList(this.queryParams)
        },
        //日期筛选
        changeDate(value) {
            this.getList(this.queryParams)
        },
        //关键字筛选
        queryRolesList: throttle(function () {
            this.getList(this.queryParams)
        }, 500),
        //删除用户
        async deleteUser(event, id) {
            this.$confirm('您正在删除用户，是否确认操作', '警告！', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        let idList
                        if (id) {
                            idList = [id]
                        } else {
                            idList = this.selectList.reduce((pre, item) => {
                                pre.push(item.id)
                                return pre
                            }, [])
                        }
                        const res = await deleteUserRequest({ idList })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message

                        })
                        this.getList(this.queryParams)
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        //分配角色
        chaneRoleType(value) {
            this.chaneRole = value
        },
        async determine() {
            let idList
            if (this.rowList) {
                idList = [this.rowList.id]
            } else {
                idList = this.selectList.reduce((pre, item) => {
                    pre.push(item.id)
                    return pre
                }, [])
            }
            if (this.title === '分配角色') {
                let roleIdList = [this.chaneRole]
                const res = await adjustUserRoleRequest({ ...this.userConfig, idList, roleIdList })
                if (res.code !== 200) return this.$message.error(res.message)
                this.$message({
                    type: 'success',
                    message: res.message

                })
            } else {
                let newSize = this.userConfig.memoryValue * 1024 * 1024 * 1024
                const res = await adjustUserSpaceRequest({ ...this.userConfig, idList, newSize })
                if (res.code !== 200) return this.$message.error(res.message)
                this.$message({
                    type: 'success',
                    message: res.message

                })
            }
            this.getList(this.queryParams)
            this.dialogVisible = false
        },
        selectable(row, index) {
            return !row.initUser
        },
        //冻结或解冻
        freezeOrThawUser(event, id, type) {
            this.$confirm(`您正在${type === 'free' ? '冻结用户' : '解冻用户'}，是否确认操作`, '警告！', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        let idList
                        if (id) {
                            idList = [id]
                        } else {
                            idList = this.selectList.reduce((pre, item) => {
                                pre.push(item.id)
                                return pre
                            }, [])
                        }
                        const res = await freezeOrThawUserRequest({
                            idList,
                            status: type === "free" ? false : true
                        })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message

                        })
                        this.getList(this.queryParams)
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        whetherShow(type) {
            if (!this.selectList.length) return true
            if (type === 'free') {
                return !this.selectList.some(item => item.enable)
            } else {
                return this.selectList.some(item => item.enable)
            }
        },
        //释放用户内存
        async clearUserSpace(event, id) {
            this.$confirm('您正在释放用户内存，是否确认操作', '警告！', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        let idList
                        if (id) {
                            idList = [id]
                        } else {
                            idList = this.selectList.reduce((pre, item) => {
                                pre.push(item.id)
                                return pre
                            }, [])
                        }
                        const res = await clearUserSpaceRequest({ idList })
                        if (res.code !== 200) return this.$message.error(res.message)
                        this.$message({
                            type: 'success',
                            message: res.message

                        })
                        this.getList(this.queryParams)
                    } else if (action === 'cancel') {
                        this.$message({
                            message: '取消操作',
                        })
                    }
                    done();
                }
            }).catch(() => { })
        },
        addOrEditUser(row) {
            this.getRoleSelect()
            if (row) {
                this.userForm = {
                    ...row,
                    roleId: row.userRoleIdList[0]
                }
                this.userTitle = '编辑用户'
            } else {
                this.userForm.mobilePhone = ''
                this.userForm.userName = ''
                this.userForm.id = ''
                this.userForm.roleId = ''
                this.userForm.password = ''
                this.userForm.email = ''
                this.userTitle = '新增用户'
            }
            this.userDialogVisible = true
        },
        async userDetermine() {
            // if (!this.userForm.mobilePhone) return this.$message.error('手机号是必填项！')
            // if (!this.userForm.roleId) return this.$message.error('用户角色是必填项！')
            const res = await saveUserRequest(this.userForm)
            if (res.code !== 200) return this.$message.error(res.message)
            this.$message({
                type: 'success',
                message: res.message
            })
            this.getList(this.queryParams)
            this.userDialogVisible = false
        },
        clearUser() {
            this.params = {
                num: 1,
                unit: '日',
            }
            this.clearVisible = true
        },
        async clear() {
            const res = await cleanInactiveUserSpaceRequest(this.params)
            if (res.code !== 200) return this.$message(res.message)
            this.$message({ type: 'success', message: res.message })
            this.clearVisible = false
            this.getList(this.queryParams)
        },
        manageControl(type, id) {
            if (this.role == '管理员') {
                if (type === '管理员' && id !== this.id || type === '超级管理员') {
                    return true
                } else {
                    return false
                }
            } else if(this.role === '超级管理员'){
                return false
            }
        }
    },
};
</script>

<style lang="scss" scoped>
.title_management {
    margin-left: 30px;
}

.content_management {
    margin: 0 15px;

    .table_management {
        border: 1px solid #d3ddeb;
        border-radius: 6px;

        .createDate {
            padding-top: 15px;
        }
    }

    .select_management {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        line-height: 50px;
        margin-bottom: 15px;

        ::v-deep .el-input__inner {
            height: 35px;
            line-height: 35px;
            border-radius: 4px;
        }

        .title {
            margin-left: 10px;
        }

    }
}

.dialog_management {
    display: flex !important;
    justify-content: space-around;
    align-items: center;
}

::v-deep .el-dialog__header {
    text-align: center;
    font-weight: 700;
}

::v-deep .el-dialog__body {
    padding: 20px;
}

::v-deep .el-dialog__footer {
    display: flex;
    justify-content: center;
}

.Memory {
    display: flex;
    align-items: center;
    padding: 0 20px;

    ::v-deep .el-slider__marks-text {
        width: 31px;
    }

    h3 {
        width: 100px;
    }

    div {
        flex: 1;
    }
}

.user_details {
    padding: 0 25px;
}

::v-deep .el-slider__marks-text {
    width: 30px;
}

::v-deep .el-form-item__content {
    max-width: 260px;
}

::v-deep .el-input__inner {
    border-radius: 6px;
}

.clear_dom {
    display: flex;
    align-items: center;
}
</style>